<template>
    <Dialog :title="title" :show="true" @close="cancel" :width="380" :height="350" :left="uiLeft" :top="uiTop">
        <div class="box">
            <div class="prop-panel">

                <div class="prop-top">
                    <div v-if="sceneObject.typeName == 'ESRtsPolygon'">
                        <div class="item1">
                            <div>是否编辑：</div>
                            <div class="edit">
                                <el-switch v-model="polygonEditingRef" size="small" />
                                <el-button @click.stop="draw"> 重新绘制</el-button>
                            </div>
                        </div>
                        <div class="item1">
                            <div>点位等高：</div>
                            <div>
                                <el-switch v-model="isHeightEqualRef" size="small" />
                            </div>
                        </div>
                        <div class="item1">
                            <div>填充颜色：</div>
                            <div class="edit">
                                <el-color-picker v-model="polygonFillColor" show-alpha size="small" />
                            </div>
                        </div>
                        <div class="item1">
                            <div>贴图：</div>
                            <div class="texture-img">
                                <el-input v-model="textureRef" style="width: 230px;" clearable
                                    @clear="textureRef = ''" />
                                <div class="list-img choose" @click="currentDialog = 'texture'" title="选择"></div>
                            </div>
                        </div>


                    </div>
                    <div v-if="sceneObject.typeName == 'ESRtsEexturedPolygon'">
                        <div class="item1">
                            <div>是否编辑：</div>
                            <div class="edit">
                                <el-switch v-model="extrudedEditingRef" size="small" />
                                <el-button @click.stop="draw"> 重新绘制</el-button>
                            </div>
                        </div>
                        <div class="item1">
                            <div>填充颜色：</div>
                            <div class="edit">
                                <el-color-picker v-model="extrudedFillColor" show-alpha size="small" />
                            </div>
                        </div>
                        <div class="row">
                            <div class="item1">
                                <div>底面高程：</div>
                                <div>
                                    <el-input-number v-model="bottomRef" controls-position="right" size="small" />
                                </div>
                            </div>
                            <div class="item1">
                                <div>柱体高度：</div>
                                <div>
                                    <el-input-number v-model="ceillingRef" controls-position="right" size="small" />
                                </div>
                            </div>
                        </div>
                        <div class="item1">
                            <div>顶面贴图：</div>
                            <div class="texture-img">
                                <el-input v-model="topTextureRef" style="width: 230px;" clearable
                                    @clear="topTextureRef = ''" />
                                <div class="list-img choose" @click="currentDialog = 'top'" title="选择"></div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="item1">
                                <div>贴图宽度：</div>
                                <div>
                                    <el-input-number v-model="topImageWidthRef" controls-position="right"
                                        @change="changeImage('topWidth', $event)" :min="0" size="small" />
                                </div>
                            </div>
                            <div class="item1">
                                <div>贴图高度：</div>
                                <div>
                                    <el-input-number v-model="topImageHeightRef" controls-position="right"
                                        @change="changeImage('topHeight', $event)" :min="0" size="small" />
                                </div>
                            </div>
                        </div>
                        <div class="item1">
                            <div>侧面贴图：</div>
                            <div class="texture-img">
                                <el-input v-model="sideTextureRef" style="width: 230px;" clearable
                                    @clear="sideTextureRef = ''" />
                                <div class="list-img choose" @click="currentDialog = 'side'" title="选择"></div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="item1">
                                <div>贴图宽度：</div>
                                <div>
                                    <el-input-number v-model="sideImageWidthRef" controls-position="right"
                                        @change="changeImage('sideWidth', $event)" :min="0" size="small" />
                                </div>
                            </div>
                            <div class="item1">
                                <div>贴图高度：</div>
                                <div>
                                    <el-input-number v-model="sideImageHeightRef" controls-position="right"
                                        @change="changeImage('sideHeight', $event)" :min="0" size="small" />
                                </div>
                            </div>
                        </div>
                    </div>

                </div>

                <div class="prop-bottom" v-if="createOrEdit == 'create'">
                    <el-button @click="add">创建</el-button>
                </div>
            </div>
        </div>
    </Dialog>
    <TexturePanel v-if="currentDialog == 'texture'" :title="'选择贴图'" :isVisible="true" @close="currentDialog = undefined"
        @confirm="chooseTextureConfirm" />
    <TexturePanel v-if="currentDialog == 'top'" :title="'选择顶面贴图'" :isVisible="true" @close="currentDialog = undefined"
        @confirm="chooseTopConfirm" />
    <TexturePanel v-if="currentDialog == 'side'" :title="'选择侧面贴图'" :isVisible="true" @close="currentDialog = undefined"
        @confirm="chooseSideConfirm" />
</template>
<script setup lang="ts">
import Dialog from "@/components/Dialog.vue";
import { getProjectManager } from "@/scripts/getProjectManager";
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import {
    toVR,
    createVueDisposer
} from "earthsdk-ui";
import TexturePanel from "./TexturePanel.vue";
import { cssColorToXe2Color, extractNumbersFromRGBA, getsceneObjNumfromSceneTree, processNum, xe2ColorToCssColor } from "@/scripts/utils";

const props = withDefaults(defineProps<{ title: string, sceneObject: any, createOrEdit: string }>(), {});
const emits = defineEmits(["cancel"]);
const cancel = () => {
    emits("cancel");
};

const uiLeft = document.body.clientWidth - 10 - 380;

// const uiLeft = 10;

const uiTop = document.body.clientHeight - document.body.clientHeight / 2;

const d = createVueDisposer(onBeforeUnmount);
const objm = getProjectManager();

const cimrtsSceneTreeWrapper = objm.cimrtsSceneTreeWrapper

const cimrtsManager = objm.cimrtsManager

const waterMend = objm.cimrtsManager.waterMend as WaterMend;
const editPolygon = objm.modelserManager.editPolygon;


// 当前选中的数据集
const currentDataSetRef = toVR<any>(d, [waterMend, "currentDataSet"]);
// 当前选中的要素类
const currentFeatureClassRef = toVR<any>(d, [waterMend, "currentFeatureClass"]);
// 当前选中的要素类名称
const currentFeatureClassNameRef = toVR<any>(d, [waterMend, "currentFeatureClassName"]);
// 切片服务名称
const tileServiceNameRef = toVR<any>(d, [cimrtsManager, "tileServiceName"]);


const currentDialog = ref<any>(undefined);


// 多边形
let polygonEditingRef: any;
let isHeightEqualRef: any
const polygonFillColor = ref('rgba(10, 233, 245, 0.4)');


let textureRef = ref("");

// 挤压多边形
let extrudedEditingRef: any;
const bottomRef = ref(0);
const ceillingRef = ref(10);
const extrudedFillColor = ref('rgba(10, 233, 245, 0.4)');

let topTextureRef = ref("");
let topImageHeightRef = ref(0);
let topImageWidthRef = ref(0);
let sideTextureRef = ref("");
let sideImageHeightRef = ref(0);
let sideImageWidthRef = ref(0);

let topRatioRef = ref("");
let sideRatioRef = ref("");

const init = () => {
    if (props.sceneObject.typeName == 'ESRtsPolygon') {

        polygonEditingRef = toVR<any>(d, [props.sceneObject, "editing"])
        isHeightEqualRef = toVR<any>(d, [props.sceneObject, "isHeightEqual"])

        // if (props.createOrEdit == 'create') {
        polygonEditingRef.value = true
        // isHeightEqualRef.value = true
        // }
        if (props.createOrEdit != 'create') {
            const fillColor = xe2ColorToCssColor(props.sceneObject.fillColor)
            polygonFillColor.value = `rgba(${fillColor[0]}, ${fillColor[1]}, ${fillColor[2]}, ${fillColor[3]})`
        }
        textureRef.value = props.sceneObject.materials.texture

        watch(polygonFillColor, () => {
            const rgba = extractNumbersFromRGBA(polygonFillColor.value)
            props.sceneObject.fillColor = cssColorToXe2Color(rgba)
        })


    }
    if (props.sceneObject.typeName == 'ESRtsEexturedPolygon') {

        extrudedEditingRef = toVR<any>(d, [props.sceneObject, "editing"])
        // if (props.createOrEdit == 'create') {
        extrudedEditingRef.value = true
        // }

        props.sceneObject.absoluteBottom = true
        props.sceneObject.absoluteCeilling = true

        if (props.createOrEdit == 'edit') {
            bottomRef.value = processNum(props.sceneObject.bottom) ?? 0
            ceillingRef.value = processNum(props.sceneObject.ceilling - props.sceneObject.bottom - (editPolygon.getMaxHeight(props.sceneObject.points) - editPolygon.getMinHeight(props.sceneObject.points))) ?? 0

            const fillColor = xe2ColorToCssColor(props.sceneObject.fillColor)
            extrudedFillColor.value = `rgba(${fillColor[0]}, ${fillColor[1]}, ${fillColor[2]}, ${fillColor[3]})`
        }

        watch(extrudedFillColor, () => {
            const rgba = extractNumbersFromRGBA(extrudedFillColor.value)
            props.sceneObject.fillColor = cssColorToXe2Color(rgba)
        })

        topTextureRef.value = props.sceneObject.materials.topTexture ?? ""
        topImageHeightRef.value = props.sceneObject.materials.topImageHeight ?? 0
        topImageWidthRef.value = props.sceneObject.materials.topImageWidth ?? 0
        sideTextureRef.value = props.sceneObject.materials.sideTexture ?? ""
        sideImageHeightRef.value = props.sceneObject.materials.sideImageHeight ?? 0
        sideImageWidthRef.value = props.sceneObject.materials.sideImageWidth ?? 0
        topRatioRef.value = props.sceneObject.materials.topRatio
        sideRatioRef.value = props.sceneObject.materials.sideRatio


        props.sceneObject.dispose(
            props.sceneObject.pointsChanged.disposableOn((e: any) => {
                bottomRef.value = editPolygon.getMinHeight(props.sceneObject.points)
                props.sceneObject.ceilling = processNum(Number(ceillingRef.value) + bottomRef.value + (editPolygon.getMaxHeight(props.sceneObject.points) - editPolygon.getMinHeight(props.sceneObject.points)));
                props.sceneObject.bottom = processNum(bottomRef.value)
            })
        );
    }
}

// 重新绘制
const draw = () => {
    if (props.sceneObject.typeName == 'ESRtsPolygon') {
        if (polygonEditingRef.value) {
            polygonEditingRef.value = false;
        }
        props.sceneObject.points = []
        polygonEditingRef.value = true;
    } else {
        if (extrudedEditingRef.value) {
            extrudedEditingRef.value = false;
        }
        props.sceneObject.points = []
        extrudedEditingRef.value = true;
    }

};


watch(() => props.sceneObject, (newVal, oldVal) => {
    init()
}, { immediate: true })



watch([bottomRef, ceillingRef], (newVal, oldVal) => {
    props.sceneObject.bottom = processNum(Number(bottomRef.value))
    props.sceneObject.ceilling = processNum(Number(ceillingRef.value) + Number(bottomRef.value) + (editPolygon.getMaxHeight(props.sceneObject.points) - editPolygon.getMinHeight(props.sceneObject.points)));
})

// 设置贴图 宽高
const changeImage = (type: string, value: number) => {
    if (type == "topWidth") {
        // @ts-ignore
        topImageWidthRef.value = Number(value)
    } else if (type == "topHeight") {
        // @ts-ignore
        topImageHeightRef.value = Number(value)
    } else if (type == "sideWidth") {
        // @ts-ignore
        sideImageWidthRef.value = Number(value)
    } else if (type == "sideHeight") {
        // @ts-ignore
        sideImageHeightRef.value = Number(value)
    }
}

// 选择材质确定按钮
const chooseTextureConfirm = (val: string) => {
    currentDialog.value = undefined
    textureRef.value = val
}

watch(textureRef, (newVal, oldVal) => {
    let materials: any = {}
    textureRef.value && (materials.texture = textureRef.value)
    props.sceneObject.materials = {
        ...materials
    }
})

watch([topTextureRef, topImageHeightRef, topImageWidthRef, sideTextureRef, sideImageHeightRef, sideImageWidthRef, topRatioRef, sideRatioRef], (newVal, oldVal) => {
    let materials: any = {}
    topTextureRef.value && (materials.topTexture = topTextureRef.value)
    materials.topImageHeight = topImageHeightRef.value
    materials.topImageWidth = topImageWidthRef.value
    sideTextureRef.value && (materials.sideTexture = sideTextureRef.value)
    materials.sideImageHeight = sideImageHeightRef.value
    materials.sideImageWidth = sideImageWidthRef.value
    topTextureRef.value && topRatioRef.value && (materials.topRatio = topRatioRef.value)
    sideTextureRef.value && sideRatioRef.value && (materials.sideRatio = sideRatioRef.value)
    props.sceneObject.materials = { ...materials }
})

const chooseTopConfirm = (val: string, ratio: any) => {
    currentDialog.value = undefined
    topTextureRef.value = val
    topRatioRef.value = ratio
}
const chooseSideConfirm = (val: string, ratio: any) => {
    currentDialog.value = undefined
    sideTextureRef.value = val
    sideRatioRef.value = ratio
}

// 添加到sceneTree上
const add = () => {
    const treeItem = objm.createdTreeItem(cimrtsSceneTreeWrapper)
    treeItem.sceneObject = props.sceneObject;
    // @ts-ignore
    treeItem.sceneObject.datasetName = currentDataSetRef.value
    // @ts-ignore
    treeItem.sceneObject.featureClassId = currentFeatureClassRef.value
    // @ts-ignore
    treeItem.sceneObject.tileServiceName = tileServiceNameRef.value

    const type = props.sceneObject.typeName == 'ESRtsPolygon' ? '多边形' : '多边形体'
    const name = "绘制对象_" + type + "_" + currentFeatureClassNameRef.value
    // @ts-ignore
    const num = getsceneObjNumfromSceneTree(treeItem.sceneObject.typeName, objm.cimrtsSceneTreeWrapper);
    treeItem.name = `${name}(${num})`
    // const type = props.sceneObject.typeName == 'ESRtsPolygon' ? '多边形' : '多边形体'
    // treeItem.name = type + getsceneObjNumfromSceneTree(props.sceneObject.typeName, cimrtsSceneTreeWrapper);
    cancel()


}



onMounted(() => {

});
onBeforeUnmount(() => {
    props.sceneObject.editing = false
});
</script>

<style scoped>
.box {
    padding: 10px 15px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 100%;
}

.prop-panel {
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.item1 {
    display: grid;
    grid-template-columns: 75px 1fr;
    align-items: center;
    margin-bottom: 8px;
}

.list-img {
    width: 25px;
    height: 25px;
    cursor: pointer;
}

.choose {
    background: url("@/assets/cimrts/propPanel/choose.png") no-repeat;
    background-size: 100% 100%;
    margin-left: 10px;
}

.texture-img {
    display: flex;
    align-items: center;

}

.prop-bottom {
    display: flex;
    justify-content: flex-end;
}

.el-input-number--small {
    width: 90px;
}

.row {
    display: flex;
    gap: 10px;
}

.edit {
    display: flex;
    gap: 20px;
    align-items: center;
}
</style>
